package com.codeying.controller;

import com.codeying.component.excel.ExcelLogs;
import com.codeying.component.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.codeying.utils.component.*;
import com.codeying.utils.*;
import com.codeying.entity.*;
import com.codeying.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.io.InputStream;
import java.util.*;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FileUtils;
import jakarta.servlet.ServletOutputStream;
/** 用户功能 关于用户增删改查等 */
@Controller
@RequestMapping({"user"})
public class UserController extends BaseController {

  /**
   * 用户列表页
   *
   * @param model
   * @param pageIndex
   * @param orderby
   * @return
   */
  @RequestMapping("list")
  public String list(Model model, Integer pageIndex, String[] orderby) {
    if (pageIndex == null) {
      pageIndex = 1; // 默认访问用户第一页,分页
    }

    IPage<User> pageInfo = new Page<User>().setCurrent(pageIndex).setSize(15); // 分页大小
    // 获取用户列表数据
    QueryWrapper<User> queryWrapper = getQueryWrapper(orderby);

    StringBuilder statisticInfo = new StringBuilder();
    {
      QueryWrapper<User> sumQueryWrapper = queryWrapper.clone();
      sumQueryWrapper.select("IFNULL(avg(age), 0) AS value"); // 设置聚合查询字段
      Map<String, Object> avgResult = userService.getMap(sumQueryWrapper); // 获取SUM结果
      BigDecimal totalSum =
          avgResult != null ? new BigDecimal(avgResult.get("value").toString()) : BigDecimal.ZERO;
      totalSum = totalSum.setScale(2, RoundingMode.HALF_UP); // 四舍五入
      statisticInfo.append("平均年龄：" + totalSum + "；");
    }
    model.addAttribute("statisticInfo", statisticInfo.toString());

    // 使用原始用户queryWrapper进行分页查询（未被修改select条件）
    pageInfo = userService.page(pageInfo, queryWrapper);
    // 获取到的用户
    List<User> userList = pageInfo.getRecords();

    // 将数据放入request

    model.addAttribute("userList", userList);
    // 将分页信息传回前端
    PagerVO pager =
        new PagerVO(
            (int) pageInfo.getCurrent(), (int) pageInfo.getSize(), (int) pageInfo.getTotal());
    model.addAttribute("pager", pager);
    return "/pages/user-list";
  }

  /**
   * 获取查询条件
   *
   * @param orderby
   * @return
   */
  private QueryWrapper<User> getQueryWrapper(String[] orderby) {
    // 用于存储查询的条件
    QueryWrapper<User> paramMap = new QueryWrapper<>();
    String username = req.getParameter("username");
    if (!StringUtils.isEmpty(username)) {
      paramMap.like("username", username);
      req.setAttribute("username", username);
    }
    String name = req.getParameter("name");
    if (!StringUtils.isEmpty(name)) {
      paramMap.like("name", name);
      req.setAttribute("name", name);
    }
    String gender = req.getParameter("gender");
    if (!StringUtils.isEmpty(gender)) {
      paramMap.eq("gender", gender);
      req.setAttribute("gender", gender);
    }

    String orderByStr = "id desc"; // 默认根据id降序排序
    if (orderby != null && orderby.length > 0) { // 如果前端传来了需要排序的字段，那么根据前端字段排序
      // 前端回显
      for (String s : orderby) {
        req.setAttribute(s.replace(" ", ""), true);
      }
      orderByStr = Arrays.toString(orderby);
      // 前端传来的排序字段都会有","开头，去掉第一个逗号
      orderByStr = orderByStr.substring(1, orderByStr.length() - 1);
    }
    // 默认按照id排序
    paramMap.last("order by " + orderByStr);
    return paramMap;
  }

  // 前往用户编辑页
  @RequestMapping("edit")
  public String edit(String id, Model model) {
    // 根据id获取
    User entity = userService.getById(id);
    if (entity == null) {
      entity = new User();
      model.addAttribute("item", entity);
      return "/pages/user-add";
    } else {
      model.addAttribute("item", entity);
      return "/pages/user-edit";
    }
  }

  // 用户详情页
  @RequestMapping("detail")
  public String detail(@RequestParam("id") String id, Model model) {
    User entity = userService.getById(id);
    model.addAttribute("item", entity);
    return "/pages/user-detail";
  }

  // 用户保存
  @RequestMapping("save")
  @ResponseBody
  public ApiResult save(User entityTemp) {
    String id = entityTemp.getId(); // 用户主键
    String username = entityTemp.getUsername(); // 用户名
    String password = entityTemp.getPassword(); // 密码
    String name = entityTemp.getName(); // 姓名
    String gender = entityTemp.getGender(); // 性别
    Integer age = entityTemp.getAge(); // 年龄
    String tele = entityTemp.getTele(); // 电话

    // 新增或更新
    if (entityTemp.getId() == null || "".equals(entityTemp.getId())) { // 新增
      id = CommonUtils.newId();
      entityTemp.setId(id);
      // 唯一字段，则在此校验
      QueryWrapper<User> wrapperusername = new QueryWrapper();
      wrapperusername.eq("username", entityTemp.getUsername());
      if (userService.list(wrapperusername).size() > 0) {
        return fail("用户名 已存在！");
      }
      // 唯一字段，则在此校验
      QueryWrapper<User> wrappername = new QueryWrapper();
      wrappername.eq("name", entityTemp.getName());
      if (userService.list(wrappername).size() > 0) {
        return fail("姓名 已存在！");
      }
      // before add

      userService.save(entityTemp);
    } else {
      // before edit

      userService.updateById(entityTemp);
      if (getCurrentUser().getId().equals(id)) { // 刷新用户session
        setSessionValue("user", userService.getById(id));
      }
    }
    return ApiResult.successMsg("操作成功"); // 返回成功
  }

  // 用户删除
  @RequestMapping("delete")
  @ResponseBody
  public ApiResult delete(String id) {
    User delTemp = userService.getById(id);
    // before del

    // 根据ID删除记录
    userService.removeById(id);
    return success();
  }

  // 从excel导入数据
  @PostMapping("excel")
  @ResponseBody
  public ApiResult importexcel(@RequestParam(value = "excel") MultipartFile excel)
      throws IOException {
    if (excel != null) {
      try {
        InputStream inputStream = excel.getInputStream();
        Collection<Map> importExcel =
            ExcelUtil.importExcel(
                Map.class, inputStream, "yyyy年MM月dd日 HH:mm:ss", new ExcelLogs(), 0);
        List<User> list = new ArrayList<>();
        for (Map m : importExcel) {
          User entity = new User();
          entity.setId(CommonUtils.newId());
          entity.setUsername((String) m.get("用户名"));
          entity.setPassword((String) m.get("密码"));
          entity.setName((String) m.get("姓名"));
          entity.setGender((String) m.get("性别"));
          Integer age = MyUtils.strToInt(((String) m.get("年龄")));
          if (age != null) {
            entity.setAge(age);
          }
          entity.setTele((String) m.get("电话"));
          list.add(entity);
        }
        userService.saveBatch(list);
        return ApiResult.successMsg("导入成功");
      } catch (Exception e) {
        e.printStackTrace();
        return ApiResult.fail("文件解析失败,请检查内容是否正确！");
      }
    } else {
      return (ApiResult.fail("请选择文件"));
    }
  }

  // 导出excel
  @RequestMapping("excel")
  public void excel() throws IOException {
    // 获取数据
    List<User> data = userService.list(getQueryWrapper(null));
    // 循环遍历list数据，统计、获取外键数据
    for (User stAv : data) {}
    HashMap<String, String> headMap = new LinkedHashMap<>();
    headMap.put("username", "用户名");
    headMap.put("password", "密码");
    headMap.put("name", "姓名");
    headMap.put("gender", "性别");
    headMap.put("age", "年龄");
    headMap.put("tele", "电话");
    Collection<Object> dataset = new ArrayList<>(data);
    resp.setHeader("Content-Disposition", "attachment; filename=" + "user.xls");
    resp.setDateHeader("expries", -1);
    resp.setHeader("Cache-Control", "no-cache");
    resp.setHeader("Pragma", "no-cache");
    ServletOutputStream servletOutputStream = null;
    try {
      servletOutputStream = resp.getOutputStream();
      ExcelUtil.exportExcel(headMap, dataset, servletOutputStream);
      servletOutputStream.close();
    } catch (IOException e) {
      System.out.println("IOException");
    }
  }
}

